﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using Newtonsoft.Json.Linq;
using TianYu.Core.Common; 

namespace TianYu.Core.Pdf.ContentElement.Text
{
    public class TextAreaElement : AbstractTextElement
    {
        /// <summary> 字段 </summary>
        public List<TextAreaField> FieldList { get; set; }

        /// <summary> 自定义内容 </summary>
        public ContentModel Content { get; set; }

        public override void Draw(PdfTemplateContent pdfTemplateContent)
        {
            var pdfContentByte = pdfTemplateContent.PdfWriter.DirectContent;

            //文本
            var columnText = new ColumnText(pdfContentByte);

            //画矩形 
            base.DrawRectangle(columnText, pdfContentByte, Math.Abs(Content.Size - 12));

            //内容
            if (FieldList != null && FieldList.Any())
            {
                var fontStyle = CommonHelper.GetFontStyle(Content.Style);
                var fontColor = (FontColor > 0) ? CommonHelper.GetBaseColor(FontColor) : BaseColor.BLACK;

                Font family = new Font(CommonHelper.GetFontFamilyPath(Content.Family), Content.Size, fontStyle, fontColor);

                Paragraph paragraph = new Paragraph();
                paragraph.SpacingBefore = 1;
                paragraph.Leading = CommonHelper.BaseLeading * Content.RowSpace;
                paragraph.Font = family;
                paragraph.Alignment = CommonHelper.GetAlignment(Content.Align);

                //数据源：正常；异常：页码等（对象数组》当前所在子项） 
                var text = string.Empty;
                foreach (var fieldTemp in FieldList)
                {
                    if (fieldTemp.Field.IndexOf('.') >= 0)
                    {
                        var dataFrom = JObject.FromObject(pdfTemplateContent.JToken);
                        //字段移除前缀
                        var field = fieldTemp.Field.Split('.')[1];

                        text = dataFrom.StringValue(field);//取值 
                    }
                    else
                    {
                        text = pdfTemplateContent.PdfObject.StringValue(fieldTemp.Field);//取值 
                    } 

                    //换行显示
                    if (fieldTemp.NewLine)
                    {
                        Paragraph paragraphTemp = paragraph;
                        paragraphTemp.Clear();//清空数据 

                        paragraphTemp.Add(text);
                        columnText.AddElement(paragraphTemp);
                    }
                    else
                    {
                        paragraph.Add(text);
                    }
                }
                columnText.AddElement(paragraph);
            }

            columnText.Go();
        }
    }
}
